0

Here I've written code to implement HttpPost request in android which should run after the onClick method.

Well, I didn't get the solution, this is the 3rd program I've tried and now updating the question.

But I don't know every time I am getting the same error. Kindly have a look of this situation.

I believe, the codes are almost correct with any small required correction, need to think differently from what I am doing here.

Because it works fine as simple java program in eclipse but android studio throws exception.

This is onClick method:

public void onClick(View v) {
    inputSub = subIn.getText().toString();
    String url = "https://some_url";
    String inputJson = null;

    try {
        inputJson = "{  \"asset\": {\"id\": ..........}";
    }catch (JSONException e){
        e.printStackTrace();
    }
    new CreateIncident(url, inputJson).execute();
}

This is AsyncTask class :

private class CreateIncident extends AsyncTask<Void, Void, Void> {
    private final String TAG = "HttpClient";

    final String user ="some_user";
    final String password ="some_pwd";

    String serUrl;
    String inputJson ="";

    public CreateIncident(String serUrl, String inputJson) {
        this.serUrl = serUrl;
        this.inputJson = inputJson;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        // Showing progress dialog
        pDialog = new ProgressDialog(CreateIncidentActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) { 
      try {
        String authString = user + ":" + password;

        byte[] authBytes = authString.getBytes();
        String authStringEnc = Base64.encodeToString(authBytes, Base64.DEFAULT);

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(serUrl);

        postRequest.setHeader("Authorization", "Basic " + authStringEnc);
        postRequest.setHeader("Accept", "application/json");
        postRequest.setHeader("Content-type", "application/json");

        StringEntity input = new StringEntity(inputJson);

        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 65728);
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        catch (IOException e) { e.printStackTrace(); }
        catch (Exception e) { e.printStackTrace(); }


        System.out.println("finalResult " + sb.toString());
        System.out.println(response.getStatusLine().getReasonPhrase());

        if (response.getStatusLine().getStatusCode() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(
                new InputStreamReader((response.getEntity().getContent())));


        httpClient.getConnectionManager().shutdown();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {
        e.printStackTrace();

    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();

    }
}

Here I am not getting any exception showing in stackTrace of Android Monitor,but after debugging I found it's throwing the exception

javax.net.ssl.SSLException: Read error: ssl=0xd6483780: I/O error during system call, Connection reset by peer

And the error-code differs sometime for the same program.

I am not able to find what mistake I am doing here.

Please somebody help me.

Shambhu
  • 181
  • 6
  • 16

1 Answers1

0

Try to Update your app level build.gradle, by adding this line

useLibrary 'org.apache.http.legacy'

into the first block/portion named as android For Example:

apply plugin: 'com.android.application'

    android {
        useLibrary 'org.apache.http.legacy'
        compileSdkVersion 26
        buildToolsVersion "26.0.0"
        defaultConfig {
            applicationId "com.example.mnaum.getgpscoordinates"
            minSdkVersion 15
            targetSdkVersion 26
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        }

and then run your program

Nauman Shafique
  • 433
  • 1
  • 6
  • 15
  • Thaks a lot. By adding this line the program executes. but now at this line `HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);` the `response` is _null_. and the _error_ is `javax.net.ssl.sslexception connection reset by peer android` – Shambhu Jul 29 '17 at 07:31