The code works in Xamarin Android but does not work in Java (HttpPost JSON)

I started developing in Xamarin and then decided that a license might be a little expensive to play, so I pass my code in java.

I have a small piece that does POST with a JSON object, and it works in Xamarin and does the work in Java.

Xamarin:

    var client = new HttpClient ();
    var content = new FormUrlEncodedContent(new Dictionary<string, string>() { 
        {"action", "getEpisodeJSON"},
        {"episode", "11813"}

    });
    client.DefaultRequestHeaders.Referrer = new Uri(link);

    var resp = client.PostAsync("http://www.ts.kg/ajax", content).Result;
    var repsStr = resp.Content.ReadAsStringAsync().Result;
    dynamic res = JsonConvert.DeserializeObject (repsStr);

Android:

    HttpClient httpclient = new DefaultHttpClient();

    // 2. make POST request to the given URL
    HttpPost httpPost = new HttpPost("http://www.ts.kg/ajax");

    String json = "";

    // 3. build jsonObject
    JSONObject jsonObject = new JSONObject();
    jsonObject.accumulate("action", "getEpisodeJSON");
    jsonObject.accumulate("episode", "11813");

    // 4. convert JSONObject to JSON to String
    json = jsonObject.toString();

    // 5. set json to StringEntity
    StringEntity se = new StringEntity(json);

    // 6. set httpPost Entity
    httpPost.setEntity(se);

    // 7. Set some headers to inform server about the type of the content
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    httpPost.addHeader("Referer", "http://www.ts.kg");

    // 8. Execute POST request to the given URL
    HttpResponse httpResponse = httpclient.execute(httpPost);

    // 9. receive response as inputStream
    InputStream inputStream = httpResponse.getEntity().getContent();

    // 10. convert inputstream to string
    String result;
    if(inputStream != null)
        result = convertInputStreamToString(inputStream);

What is the correct way to make such a POST on Android?

UPD The current problem is that I get an empty result string;

    private static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }
+4
source share
1 answer

Fiddle ( : http://tech.vg.no/2014/06/04/how-to-monitor-http-traffic-from-your-android-phone-through-fiddler/)

cookie, HttpContex, : Android HttpClient Cookie

Content-Type, :

httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
+2

All Articles