How to Make an HTTP POST with JSON object as data? - java

Can anyone refer me to a single, simple resource explaining how to in Java make an HTTP POST with JSON object as data? I want to be able to do this without using Apache HTTP Client.
The following is what I've done so far. I am trying to figure out how to modify it with JSON.
public class HTTPPostRequestWithSocket {
public void sendRequest(){
try {
String params = URLEncoder.encode("param1", "UTF-8")
+ "=" + URLEncoder.encode("value1", "UTF-8");
params += "&" + URLEncoder.encode("param2", "UTF-8")
+ "=" + URLEncoder.encode("value2", "UTF-8");
String hostname = "nameofthewebsite.com";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket socket = new Socket(addr, port);
String path = "/nameofapp";
// Send headers
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
wr.write("POST "+path+" HTTP/1.0rn");
wr.write("Content-Length: "+params.length()+"rn");
wr.write("Content-Type: application/x-www-form-urlencodedrn");
wr.write("rn");
// Send parameters
wr.write(params);
wr.flush();
// Get response
BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
wr.close();
rd.close();
socket.close();//Should this be closed at this point?
}catch (Exception e) {e.printStackTrace();}
}
}

JSON is just a string.
Just add the json objet as a post value.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("jsonData", new JSONObject(json)));//json
params.add(new BasicNameValuePair("param1", "somevalue"));//regular post value

Related

How to get only Json content from HttpEntity Java

Using HttpEntity I am getting a very long text which has special characters as well along with Json.
I tried regex but it's not working as it is almost 30000 of characters.
Is there a way that i can only get Json data from the HttpEntity. Even string split did not work since it has so many of special characters.
public JSONObject sendGet(String URL, String userName, String password) throws Exception {
getRequest = new HttpGet(URL);
getRequest.addHeader("User-Agent", USER_AGENT);
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
provider.setCredentials(AuthScope.ANY, credentials);
client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
response = client.execute(getRequest);
HttpEntity entity = response.getEntity();
outputFile = new File(directoryPath + "/target/response.txt");
fos = new FileOutputStream(outputFile);
headers = response.getAllHeaders();
bw = new BufferedWriter(new OutputStreamWriter(fos));
for (Header header: headers) {
bw.write(header.getName() + ": " + header.getValue() + "\n");
}
bw.write(response.getEntity());
bw.write("Response Code : " + response.getStatusLine());
String content = EntityUtils.toString(entity); //When i print content it has string other than json as well
JSONObject obj = new JSONObject(content); //Here i receive A JSONObject text must begin with '{' at 1 [character 2 line 1]
JSONArray keys = obj.names();
Object test = JSON.parse(content);
jsonFiles = new File(directoryPath + "/JsonFiles/test.json");
fos = new FileOutputStream(jsonFiles);
bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(content);
bw.close();
return obj;
}
Try adding the following Headers:
getRequest.addHeader("Accept", "application/json");
getRequest.addHeader("Content-Type", "application/json");
getRequest.addHeader("Accept-Charset", "utf-8");

Passing json array in a key value pair in Java

I'm trying to send data using rest webservice in Java. I'm able to post data using Java in POST but now I need to send data in rawModeData and I also need to send JSONArray in surveysData key.
Please find the attached screenshot
This is the Code that I'm using to send data
try {
URL url = new URL(webServiceData.getSyncSurveyDataUrl());
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// ConnectionType
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setAllowUserInteraction(false);
httpURLConnection.setRequestProperty("charset", "utf-8");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Create the output form content
OutputStream out = httpURLConnection.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
JSONObject objects = new JSONObject();
objects.put("constituency", constituency);
objects.put("longitude", longitude);
objects.put("latitude", latitude);
objects.put("createdOn", createdOn);
for (Map.Entry<String, String> map : linkedHashMap.entrySet()) {
objects.put(map.getKey(), map.getValue());
}
writer.write("createdByDeviceId");
writer.write("=");
writer.write(URLEncoder.encode(loginModel.getDeviceId(), "UTF-8"));
writer.write("&");
writer.write("createdByMobileNumber");
writer.write("=");
writer.write(URLEncoder.encode(loginModel.getMobileNumber(), "UTF-8"));
writer.write("&");
writer.write("state");
writer.write("=");
writer.write(URLEncoder.encode(loginModel.getLoggedInState(), "UTF-8"));
writer.write("&");
writer.write("eventId");
writer.write("=");
writer.write(URLEncoder.encode(loginModel.getEventId(), "UTF-8"));
writer.write("&");
writer.write("surveysData");
writer.write("=");
writer.write(URLEncoder.encode(objects.toString(), "UTF-8"));
if (httpURLConnection.getResponseCode() != 200) {
System.out.println("Exception in 200: " + httpURLConnection.getResponseCode());
System.out.println("Exception Message: " + httpURLConnection.getResponseMessage());
/*errorLabel.setText(httpURLConnection.getResponseMessage());
errorLabel.setVisible(true);*/
}
} catch (Exception e) {
return false;
}
I'm getting 401 error message
I think you missed some authentication token in headers. Something like : httpURLConnection.setRequestProperty("tokenKey", "yourAuthToken");
You are not connecting to connection. Also I think that you need to setFixedLengthStreamingMode on connection and write output as byte array. Example:
//...
String queryParameters = formatQueryParameters(requestData);
byte[] output = queryParameters.getBytes(Charset.forName("UTF-8"));
connection.setFixedLengthStreamingMode(output.length);
connection.connect();
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.write(output);
//...
public static String formatQueryParameters(Map<String, String> requestData) throws UnsupportedEncodingException {
String equals = URLEncoder.encode("=", "UTF-8");
String ampersand = URLEncoder.encode("&", "UTF-8");
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> entry : requestData.entrySet()) {
String encodedKey = URLEncoder.encode(entry.getKey(), "UTF-8");
String encodedValue = URLEncoder.encode(entry.getValue(), "UTF-8");
builder.append(encodedKey).append(equals).append(encodedValue).append(ampersand);
}
builder.deleteCharAt(builder.lastIndexOf(ampersand));
return builder.toString();
}

Senig an HTTP request doesn't get me to the "service" function in my servlet

I am trying to do a simple servlet connection socket,
I am able to see this webpage and able to get to my servlet(on another eclipse instance) breakpoint when using a web browser.
but when i try to perform the following function:
public void Connect() {
try {
String params = URLEncoder.encode("ID", "UTF-8")
+ "=" + URLEncoder.encode("test", "UTF-8");
params += "&" + URLEncoder.encode("GOAL", "UTF-8")
+ "=" + URLEncoder.encode("Security", "UTF-8");
URL url = new URL(_address);
String host = url.getHost();
int port = url.getPort();
String path = url.getPath();
Socket socket = new Socket(host, port);
// Send headers
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
wr.write("GET " + path + " HTTP/1.0\r\n");
wr.write("Content-Length: " + params.length() + "\r\n");
wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
wr.write("\r\n");
// Send parameters
wr.write(params);
wr.flush();
// Get response
BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
String answer = "";
while ((line = rd.readLine()) != null) {
answer += line;
}
wr.close();
rd.close();
if (answer.indexOf(resourceStrings.ACCESS_GRANTED) != -1)
{
_result = true;
}
}
catch (Exception e) {
_result = false;
}
}
I just recieve the following answer:
HTTP/1.1 302 Found
Server: Apache-Coyote/1.1
Location: http://localhost:8180/Admin/
Date: Mon, 18 Apr 2016 15:00:28 GMT
Connection: close
without getting to my servlet code's breakpoint or retrieve any data from my "service" function in the servlet.
I am using Tomcat 7 if it makes any difference, do you have any idea what is causing this issue?
The parameters of a GET request are sent by appending them to the URL, not in the body of the request.

When I do not use from a condition I can get the data from php, But when I use from a condition, I Can not get data from php

My php code is correct. But I have a strange problem when I use a condition in my code. My php code sends the "A" string from server to android. In the following code when I do not use a condition in my code in the GetText() method, I can get the A string and display it in the TextView well. But when I use a condition as follows, I can not get and display the A string in the TextView . Please help me. I do not know that where is this problem.
Pass = pass.getText().toString();
// Create data variable for sent values to server
String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(Name, "UTF-8");
data += "&" + URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(Email, "UTF-8");
data += "&" + URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(Login, "UTF-8");
data += "&" + URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode(Pass, "UTF-8");
String text = "";
BufferedReader reader = null;
// Send data
try{
// Defined URL where to send data
URL url = new URL("http://127.0.0.1:8080/apps/reg.php");
// Send POST data request
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null){
// Append server response in string
sb.append(line);
}
text = sb.toString();
} catch(Exception ex){
} finally{
try{
reader.close();
} catch(Exception ex){}
}
// Show response on activity
String A = "A";
if(text.equals(A)){
content.setText(text); //it can not display the text in the TextView
}
}

Send information from PHP to Java

I want to send some information from PHP to Java. Why? Because I have a database on my server, and I get information from my database using PHP scripts.
Now I want to send that information to my client in Java. How can I do that?
I send information from Java to PHP by POST, and it works well, but I don't know how can I do the reverse.
Can you help me?
I saw this code, from a GET connection in Java... is it correct?
public String HttpClientTutorial(){
String url = "http://testes.neoscopio.com/myrepo/send.php";
InputStream content = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
content = response.getEntity().getContent();
} catch (Exception e) {
Log.e("[GET REQUEST]", "Network exception", e);
}
String response = content.toString();
return response;
}
P.S: I'm an android developer, not a Java developer...
From exampledepot: Sending POST request (Modified to get the output of your send.php.)
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
// Send data
URL url = new URL("http://testes.neoscopio.com/myrepo/send.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
}
P.S. This should work fine on Android. :)
(I usually import static java.net.URLEncoder.encode but that's a matter of taste.)

Categories

Resources