0

HttpUrlConnection POST request not working. Tell me if there is any other way to make POST request in android.Tell me if there is any other way to make POST request in android.Tell me if there is any other way to make POST request in android.

 public final String apiCall(String pUrl) {
    if( ! isInternetAvailable() )
        return "NO_INTERNET";

    try {
        URL lUrl = new URL(pUrl.replace(" ", "%20"));
        Log.i("url", String.valueOf(lUrl));

       String url = pUrl;

        Log.i("dom", url.substring(0, (url.indexOf('?') - 1)));
        Log.i("para", url.substring((url.indexOf('?') + 1), url.length()) );

        URL obj = new URL(url.substring(0,(url.indexOf('?')-1)));
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "GYUserAgentAndroid");
        con.setRequestProperty("Content-Type", "application/json");

        String urlParameters = url.substring((url.indexOf('?')+1), url.length());
        Log.i("urlParameters", urlParameters.toString());

        // Send post request
        con.setDoInput(true); // true if we want to read server's response
        con.setDoOutput(true); // false indicates this is a GET request
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();


        Log.i("res",response.toString());
        return response.toString();

    }catch (Exception e) {
        Log.i("secondEx",e.toString());
        return "ERROR";
    }

}
suraj shinde
  • 230
  • 1
  • 7
  • 19
  • I advice you to use Retrofit -It is a type-safe HTTP client for Android and Java. here you can study this http://square.github.io/retrofit/ – Pranav MS Apr 18 '17 at 10:29

2 Answers2

0

Try this

InputStream inputStream; 
HttpURLConnection urlConnection; 
byte[] outputBytes;

public class WebServiceAsyncTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {

        try {
            URL url = new URL(Url);
            urlConnection = (HttpURLConnection) url.openConnection();
            outputBytes = query.getBytes("UTF-8");
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setConnectTimeout(15000);
            urlConnection.connect();

            OutputStream os = urlConnection.getOutputStream();
            os.write(outputBytes);
            os.flush();
            os.close();

            inputStream = new BufferedInputStream(urlConnection.getInputStream());
            ResponseData = convertStreamToString(inputStream);

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

        }
        return ResponseData;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);


    }

    public String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append((line + "\n"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

Pass your parameters in json string format like this

JSONObject() params = new JSONObject();
params.put("key","your parameter");
params.put("key","your parameter");

query=params.toString();

Check this link for reference

AbhayBohra
  • 2,047
  • 24
  • 36
  • outputBytes ? query? – suraj shinde Apr 18 '17 at 10:33
  • query is the parameters which you send to the post api. It is in json String format – AbhayBohra Apr 18 '17 at 10:39
  • is there necessary to create JSONObject , bcoz I've directly assigned parameters string to string variable like this String urlParameters = url.substring((url.indexOf('?')+1), url.length()); and .urlParameters.getBytes("UTF-8"); – suraj shinde Apr 18 '17 at 10:56
  • Well it depends on your requirement..If it requires paramenters in json format then you have to use it otherwise you can send that too..Try it – AbhayBohra Apr 18 '17 at 10:59
0

Another way to perform requests is Retrofit

You can find a good tutorial here

an_droid_dev
  • 1,136
  • 14
  • 18