Sending JSON over HTTP POST with Java - 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+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1sbnM6eG1wTU09Im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AAgEDBAIDAQAAAAAAAAAAAAER8CExEGGR0UFRcaGxwf/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='}"

As per Wormbo said at the comment, your JSON should look like this :
{"a":"b","image":"/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAA8AAD/4QMraHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjAtYzA2MSA2NC4xNDA5NDksIDIwMTAvMTIvMDctMTA6NTc6MDEgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFk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MxQRIz8BGBgkODNBIBAAAAAAAAAAAAAAAAAAAAMBMAAgEDBAIDAQAAAAAAAAAAAAER8CExEGGR0UFRcaGxwf/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.

Related

Microsoft Cognitive Services - Bing Speech to Text with JAVA - curl to http request

i want to code a java http request for posting audio file (wav) for speech to text transformation.
I´m quite new to http requests, and could not find any useful hints how to achieve that.
In https://www.microsoft.com/cognitive-services/en-us/Speech-api/documentation/GetStarted/GetStarted-cURL I was able to get token (Step 1 in url), but now I am struggeling with step 2.
Can someone help or even provide java code for step 2 (post wav file to cognitive services).
CURL Request given:
curl -v -X POST "https://speech.platform.bing.com/recognize? scenarios=smd&appid=D4D52672-91D7-4C74-8AD8- 42B1D98141A5&locale=your_locale&device.os=your_device_os&version=3.0&format=json&instanceid=your_instance_id&requestid=your_request_id" -H 'Authorization: Bearer your_access_token' -H 'Content-type: audio/wav; codec="audio/pcm"; samplerate=16000' --data-binary #your_wave_file
My Java HTTP code so far (Using Apache):
HttpClient client = HttpClientBuilder.create().build();
String url = "https://speech.platform.bing.com/recognize";
String appId = "D4D52672-91D7-4C74-8AD8-42B1D98141A5"; //Always use this. See Docu
String token = "12345"; // received from step 1 (see MS documentation)
String locale = "de-DE";
String deviceOS = "Windows";
String version = "3.0";
String format = "json";
String instanceid = UUID.randomUUID().toString();
String scenarios = "smd";
// setting up post parameters
Map<String, String> postParameters = new HashMap<>();
postParameters.put("scenarios", scenarios);
postParameters.put("appid", appId);
postParameters.put("locale", locale);
postParameters.put("device.os", deviceOS);
postParameters.put("format", format);
postParameters.put("instanceid", instanceid);
postParameters.put("requestid", instanceid);
postParameters.put("version", version);
// setting up HttpPost
HttpPost httpPost = new HttpPost(url);
// PARAMETERS
List<NameValuePair> qparams = new ArrayList<>();
for (Map.Entry<String, String> s : postParameters.entrySet()) {
qparams.add(new BasicNameValuePair(s.getKey(), s.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(qparams));
// HEADERS
String wavFile = "C:\\Folder\\AudioData.wav";
Map<String, String> postHeaders = new HashMap<>();
postHeaders.put("Authorization", "Bearer " + token);
postHeaders.put("Content-Type", "audio/wav; codec=\"audio/pcm\"; samplerate=16000");
for (Map.Entry<String, String> entry : postHeaders.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
// WAV FILE
File file = new File(wavFile);
FileBody bin = new FileBody(file, ContentType.DEFAULT_BINARY);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("bin", bin);
HttpEntity reqEntity = builder.build();
httpPost.setEntity(reqEntity);
// RESPONSE
HttpResponse response = client.execute(httpPost);
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
My Response code is 200, but my response.getEntity().getContent() is empty. I expect a JSON there.
btw: if i fire this up with curl (with set parameters of course) it works, and I get a JSON back with recognized speech to text.
Can you help me with that?
Nycon

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!

Error in http connection java.lang.IllegalArgumentException: Illegal character in query at index 76

I am getting an error in http connection java.lang.IllegalArgumentException: Illegal character in query at index 76.
Tried all the 3 examples.Unable to fix it .Tried url_encode but its not taking the components:locality part into consideration.How do I make this url work .Thanks in Advance.
BufferedReader in = null;
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet();
URI website = new URI("http://maps.googleapis.com/maps/api/geocode/json?components=locality:Spokane|country=us|administrative_area:washington&address="+newText+"&sensor=false");
request.setURI(website);
HttpResponse response = httpclient.execute(request);
in = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = in.readLine();
data = line;
suggest = new ArrayList<String>();
And
String uri =("http://maps.googleapis.com/maps/api/geocode/json?components=locality:Spokane|country=us|administrative_area:washington&address="+newText+"&sensor=false");
uri=URLEncoder.encode(uri,"UTF-8");
HttpClient hClient = new DefaultHttpClient();
HttpGet hGet = new HttpGet(uri);
ResponseHandler<String> rHandler = new BasicResponseHandler();
data = hClient.execute(hGet,rHandler);
suggest = new ArrayList<String>();
And
String urlstr="http://maps.googleapis.com/maps/api/geocode/json?";
String str_parameters = "components=locality:Spokane|country=us|administrative_area:washington";
String encodedparams = URLEncoder.encode(str_parameters,"UTF-8")+"&address="+URLEncoder.encode(newText, "UTF-8")+"&sensor="+URLEncoder.encode("false", "UTF-8");
String str_finalurl=urlstr+encodedparams;
The character at 76 is |, which might be the cause of the issue. Have you tried replacing it with the hexadecimal format %7C, forming this: http://maps.googleapis.com/maps/api/geocode/json?components=locality:Spokane%7Ccountry=us%7Cadministrative_area:washington&address="+newText+"&sensor=false?
Also, is newText defined?

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

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);

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