Java Reading JSON from http request on php - Bad Request 400 - java

Im willing to read a simple json file from a http request.
This is the URL im tryng to read:
http://tccdahora.servehttp.com/teste.php
So, ive got a method to convert a URL into JSON, however its not working, ive tryed many different ways or gettin a header on post, however no success.
This is the method:
public static JSONArray getPostJSONObject(String url) throws Throwable {
// faz o POST na pagina php e obtem o inputstream de resposta
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url); // "http://tccdahora.servehttp.com/teste.php"
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setHeader("host", url);
//httppost.setHeader("Content-Type", "application/json");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
// transforma o que o php printar em uma strigzona
JSONArray jArray;
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String result = sb.toString();
Log.e("", result);
// transformando em uma array de objetos JSON
jArray = new JSONArray(result);
return jArray;
}
Is there something i am doing wrong ? Im recieving bad request error, and the string from the post is returning a HTML CODE informing the error, not the json as my browser shows.
Thanks alot for the attention !

Remove the following line:
httppost.setHeader("host", url);

Related

How send a json to server

I have a json that will be send to server in "Post".
There are parameters in json for 3 images to upload on server using multipart. I have no additional parameter to send it Multipart.
When I try it "PostMan" app of chrome to test it.
Here are 2 cases-
case 1:- select "raw" option in body & set content type "application json" in POSTMAN
Then all data had send to server expect images.
Case 2: Select "form-data" option in PostMan.
I have only to send some part of Json like images, certificates, venue, address, contact, achievement, level, at_home, certified, but unable to failed "coach_free_batch","coach_session" & "sports" section of json.
Please provide solution to upload all fields on server
Either idea to send "sports","coach_free_session" in second case by Postman or any other idea
Json
{"coach_free_batch":[{"sport_id":"10","batch_timing":{"end_time":"1:51 PM","start_time":"12:51 PM"},{"end_time":"11:51 AM","start_time":"10:51 AM"},{"end_time":"1:51 PM","start_time":"11:51 AM"}]},
{"sport_id":"4","batch_timing":[{"end_time":"1:52 PM","start_time":"12:52 PM"},
{"end_time":"3:52 PM","start_time":"2:52 PM"},{"end_time":"3:54 PM","start_time":"2:52 PM"}]}],
"coach_session":[{"timing":"2 Hour","rate":"24"},{"timing":"1 Hour","rate":"40"},
{"timing":"3 Hour","rate":"70"}],
"achievement":" national level",
"level":"Competitive","user_token":"XJnQCAz1ssuUCjgHtFs6","at_home":"1",
"sports":[{"user_sports_label_id":"7","sport_id":"2"},{"user_sports_label_id":"10","sport_id":"3"},
{"user_sports_label_id":"3","sport_id":"4"}],
"images":[{"image":"xxx"},
{"image":"xxx"}],
"experience":" more than 2 year","venue":"address","contact":"8236968542",
"certificates":[{"certificate":"certificate1"},{"certificate":"certifocate2"},{"certificate":"certificate3"}]}
Method for send Data as raw
public static String sendDataInJSONFormat(String url, String json) {
// initialize
InputStream is = null;
String result = null;
String url1 = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-Type",
"multipart/form-data; application/json; charset=UTF-8;text/plain");
HttpParams httpParameters = new BasicHttpParams();
int timeoutSocket = 25000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
StringEntity se = new StringEntity(json.toString(), "UTF-8");
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
e.printStackTrace();
}
return result;
}

Sending JSON over HTTP POST with Java

sender
StringBuilder builder = new StringBuilder();
HttpParams httpParameters=new BasicHttpParams();
HttpResponse response;
HttpPost httpPost = new HttpPost(address);
StringEntity entity = new StringEntity(JSON.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient(httpParameters);
response = client.execute(httpPost);
receiver
StringBuffer jb = new StringBuffer();
String line = null;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
json_in = org.json.HTTP.toJSONObject(jb.toString());
JSONObject js=new JSONObject((String)json_in.get("Method"));
Map<String, String> dict = new HashMap<>();
Iterator it=js.keys();
while(it.hasNext()){
String key=(String)it.next();
dict.put(key,(String) js.get(key));
}
Hi, I'm trying to pass JSON using http post, The error comes from line JSONObject js=new JSONObject((String)json_in.get("Method"));
org.json.JSONException: Unterminated string at 314 [character 315 line 1]
How it can be fixed?
Thanks.
Edit:
this request is working without problems
curl http://localhost:8080/ --data "{'a':'b','image':'
/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAA8AAD/4QMraHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjAtYzA2MSA2NC4xNDA5NDksIDIwMTAvMTIvMDctMTA6NTc6MDEgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHht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wDAQACEQMRAAAB5ds7BLDRjahSZDDDBQdmodmJf//aAAgBAQABBQJa5BusxTZ63IlAobhqeTI8jGUD3ucYf//aAAgBAgABBQLSi4IXH//aAAgBAwABBQKi1H//2gAIAQICBj8CH//aAAgBAwIGPwIf/9oACAEBAQY/Ank3HVHMzQuvsPv33GILjATW875plOMyVbaHnXqieeUV6tCdTiacEKse1eHZ46r/2gAIAQEDAT8he9t3d5uN+ujrvxliEj61UxYGkms+2R8plPl+CfRtL+xTRfwdk+eN9B//2gAIAQIDAT8hQbuR+iEkezAQ5yf/2gAIAQMDAT8hbPBIydDPB0f/2gAMAwEAAhEDEQAAECKKez//2gAIAQEDAT8QcqibGJIIOgtEmhHLKXOStTftncTmtpthr9D8NlUyVmt3CFB2lWCkm/ict56Xzov/2gAIAQIDAT8QtIkinCI+g6SRM2tHRCGDODJT0f/aAAgBAwMBPxC4JRKCX0SkbRJ/DN4HjSOB/9k='}"
As per Wormbo said at the comment, your JSON should look like this :
{"a":"b","image":"/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAA8AAD/4QMraHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjAtYzA2MSA2NC4xNDA5NDksIDIwMTAvMTIvMDctMTA6NTc6MDEgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA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BAIDAQAAAAAAAAAAAAER8CExEGGR0UFRcaGxwf/aAAwDAQACEQMRAAAB5ds7BLDRjahSZDDDBQdmodmJf//aAAgBAQABBQJa5BusxTZ63IlAobhqeTI8jGUD3ucYf//aAAgBAgABBQLSi4IXH//aAAgBAwABBQKi1H//2gAIAQICBj8CH//aAAgBAwIGPwIf/9oACAEBAQY/Ank3HVHMzQuvsPv33GILjATW875plOMyVbaHnXqieeUV6tCdTiacEKse1eHZ46r/2gAIAQEDAT8he9t3d5uN+ujrvxliEj61UxYGkms+2R8plPl+CfRtL+xTRfwdk+eN9B//2gAIAQIDAT8hQbuR+iEkezAQ5yf/2gAIAQMDAT8hbPBIydDPB0f/2gAMAwEAAhEDEQAAECKKez//2gAIAQEDAT8QcqibGJIIOgtEmhHLKXOStTftncTmtpthr9D8NlUyVmt3CFB2lWCkm/ict56Xzov/2gAIAQIDAT8QtIkinCI+g6SRM2tHRCGDODJT0f/aAAgBAwMBPxC4JRKCX0SkbRJ/DN4HjSOB/9k="}
I checked the JSON with a pretty-print formatter here and it shows the same error in your app.

Http post request to php script

I have a java program which makes an http post request to a php script on my website. Here is the code. I am also using the new Apache HTTP Components API. Here is a link to the download -> http://hc.apache.org/downloads.cgi
public static void main(String args[]) throws ClientProtocolException, IOException
{
HttpPost httppost = new HttpPost("http://ftstoo.com/public_html/TheFinalTouchSecurity/Database/test.php");
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("name", "Cannon"));
httppost.setEntity(new UrlEncodedFormEntity(parameters));
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httppost);
HttpEntity resEntity = httpResponse.getEntity();
// Get the HTTP Status Code
int statusCode = httpResponse.getStatusLine().getStatusCode();
// Get the contents of the response
InputStream in = resEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString()); //Prints the string content read from input stream
reader.close();
}
}
My test.php file is located at http://ftstoo.com/public_html/TheFinalTouchSecurity/Database/test.php
Here is my php code.
<?php
$name = $_POST['name'];
echo "Success, . $name . !";
?>
The output I am getting when I run the java program is the html from a redirecting page on my website that says the page does not exist. I want the output to return a string that says "Success, Cannon!" I think there are probably several things I am doing wrong, but if someone could please give me a hand I would really appreciate it!

Corrupted Json in Android Eclipse

im having a strange problem when receiving json results from the server. I have no idea what the problem is. The thing is that my String json result is corrupted, with strange symbols.
The result is like this (taken from eclipse debug)
Image :
Another strange thing that happens is that when I change the URL of the service to an alternative one, it works and the data is not corrupted. The URLs are the same but once redirects everything to the other.
The URL is use always is (example) http://www.hello.com
The URL that works is http://www.hello.com.uy
(cant post the exact link for security reasons)
The second one redirects everything to the first one, its the only thing it does.
I have tried changing the encoding to UTF-8 and it is still not working, here is the code (with one of the URLs commented)
I have also tried using Dev HTTP Client extension from chrome to check the service and it works fine, no corrupted data. Also, it works perfectly on iOS so i think its just and android/java issue.
DevClient:
try {
JSONObject json = new JSONObject();
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient client = new DefaultHttpClient(httpParams);
//String url = TAG_BASEURL_REST +"Sucursal";
String url = "http://www.-------.com/rest/Sucursal";
//String url = "http://www.--------.com.uy/rest/Sucursal";
HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String jsonRes = sb.toString();
JSONArray jObj = new JSONArray(jsonRes);
return jObj;
}
} catch (Throwable t) {
Log.i("Error", "Request failed: " + t.toString(), t);
}
return null;
InputStream is = entity.getContent();
// check if the response is gzipped
Header encoding = response.getFirstHeader("Content-Encoding");
if (encoding != null && encoding.getValue().equals("gzip")) {
is = new GZIPInputStream(is);
}

Android Java strange issue building URL

So I'm building an URL to be called to get a JSON response but facing a strange issue. Building the URL as shown below returns "Not found" but for testing purposes I just built the URL as such "http://api.themoviedb.org/3/search/person?api_key=XXX&query=brad" and didn't append anything and that returned the correct response. Also tried not encoding "text" and same thing...Not found. Any ideas?
StringBuilder url = new StringBuilder();
url.append("http://api.themoviedb.org/3/search/person?api_key=XXX&query=").append(URLEncoder.encode(text, ENCODING));
Log.v("URL", url.toString());
try {
HttpGet httpRequest = null;
httpRequest = new HttpGet(url.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream input = bufHttpEntity.getContent();
String result = toString(input);
//JSONObject json = new JSONObject(result);
return result;
Try using the code I have below. I've copied and pasted it out of some code I use and I know it works. May not solve your problem but I think its worth a shot. I've edited it a little bit and it should just be copy and paste into your code now.
HttpGet request = new HttpGet(new URI(url.toString()));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONObject jResponse = new JSONObject(builder.toString());

Categories

Resources