I have the following class that return an spefic field from json response.
The method to request here is with post. How can i do it with get method?
Also i want to make the get request with headers
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(
"");
post.addHeader("Auth-Token", authenticationValues.getAuthToken());
post.addHeader("device-id", authenticationValues.getDeviceId());
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("task", "savemodel"));
String generatedJSONString = null;
params.add(new BasicNameValuePair("code", generatedJSONString));
CloseableHttpResponse response = null;
Scanner in = null;
try {
post.setEntity(new UrlEncodedFormEntity(params));
response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
in = new Scanner(entity.getContent());
while (in.hasNext()) {
JsonString += in.next();
}
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println(JsonString);
JSONObject jsonObject = new JSONObject(JsonString);
JSONObject myResponse = jsonObject.getJSONObject("login");
Object myResponse2 = myResponse.get("loginStatus");
System.out.println(myResponse2);
Try this...
URL url = new URL("http://"...);
HttpURLConnection http = (HttpURLConnection)
url.openConnection();
http.setRequestMethod("GET");
http.setDoOutput(true);
http.connect();
OutputStream out = http.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(FOO);
writer.flush();
writer.close();
InputStreamReader in = new InputStreamReader(http.getInputStream());
BufferedReader br = new BufferedReader(in);
char[] chars = new char[BUF_SIZE];
int size = br.read(chars);
String response = new String(chars).substring(0, size);
All enclosed in a try-catch block.
Related
i need to pass to this URL a parameter http://192.168.1.15:8888/android_login_api/getsPreferiti.php?id="+mParam1
where mParam1 contains this String 5a325bc1b214c5.50816853
how can i do?
PS:now i get this: Response from url: {"error":false,"message":"VIDEOs fetched successfully.","pdfs":[]} but pdfs array have pdfs
Add parameters to HTTPURL Connection using HTTPPost
URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("parameter1", parameterValue1));
params.add(new BasicNameValuePair("parameter2", parameterValue2));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
conn.connect();
private String getQuery(List<NameValuePair> params) throws
UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
String response = null;
int GET = 1;
int POST = 2;
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
And you can call this method by using AsyncTask as follow:
try {
JSONObject jData = new JSONObject();
String mParam = "5a325bc1b214c5.50816853";
jData.put("id", mParam);
List<NameValuePair> params1 = new ArrayList<NameValuePair>(2);
params1.add(new BasicNameValuePair("data", jData.toString()));
response = makeServiceCall("http://192.168.1.15:8888/android_login_api/getsPreferiti.php", 1, params1);
} catch (JSONException e) {
e.printStackTrace();
}
Some commands like HttpClient or HttpPost are not working. Could anyone help me?
#Override
protected users doInBackground(Void... params){
Map<String, String> dataToSend = new HashMap<>();
dataToSend.put("x", users.x + "");
dataToSend.put("y", users.y);
URL url = new URL(SERVER_ADRESS);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
HttpParams httpRequestPramas = new BasicHttpParams();
conn.setConnectionTimeout(httpRequestPramas, CONNECTION_TIME);
HttpConnectionParams.setSoTimeout(httpRequestPramas, CONNECTION_TIME);
HttpClient client = new DefaultHttpClient(httpRequestPramas);
HttpPost post = new HttpPost(SERVER_ADRESS + "login.php");
users returnedusers = null;
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
HttpResponse httpResponse = client.execute(post);
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
JSONObject jObject = new JSONObject(result);
if (jObject.length() == 0){
users = null;
}else{
String vorname = jObject.getString("y");
int kundennummer = jObject.getInt("x");
returnedusers = new users(users.y, users.x);
}
}catch (Exception e){
e.printStackTrace();
}
return returnedusers;
}
Thanks for the help.
Try this way
URL url = new URL("http://example.sitedemo.service.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
Uri.Builder builder = new Uri.Builder().appendQueryParameter("username", "maven")
.appendQueryParameter("password", "123");
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
InputStream in = new BufferedInputStream(conn.getInputStream());
response = IOUtils.toString(in, "UTF-8");
ref- android.net.Uri.Builder
Fiends, i sending JSON String with three parameters to java web service method. but on java side method cant print in console. Please guide me what i have to change from below code?
String json = "";
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", "ghanshyam");
jsonObject.put("country", "India");
jsonObject.put("twitter", "ghahhd");
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
// 6. set httpPost Entity
System.out.println(json);
httpPost.setEntity(se);
httpGet.se
// 7. Set some headers to inform server about the type of the content
//httpPost.addHeader( "SOAPAction", "application/json" );
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
//String s = doGet(url).toString();
Toast.makeText(getApplicationContext(), "Data Sent", Toast.LENGTH_SHORT).show();
Use the following code to post the json to Java web-service: and get the resopnse as a string.
JSONObject json = new JSONObject();
json.put("name", "ghanshyam");
json.put("country", "India");
json.put("twitter", "ghahhd");
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json");
post.setEntity(new StringEntity(json.toString(), "UTF-8"));
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse httpresponse = client.execute(post);
HttpEntity entity = httpresponse.getEntity();
InputStream stream = entity.getContent();
String result = convertStreamToString(stream);
and Your convertStremToString() method will be as follows:
public static 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();
}
I have to make a http Post request using a JSON string I already have generated.
I tried different two different methods :
1.HttpURLConnection
2.HttpClient
but I get the same "unwanted" result from both of them.
My code so far with HttpURLConnection is:
public static void SaveWorkflow() throws IOException {
URL url = null;
url = new URL(myURLgoeshere);
HttpURLConnection urlConn = null;
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.connect();
DataOutputStream output = null;
DataInputStream input = null;
output = new DataOutputStream(urlConn.getOutputStream());
/*Construct the POST data.*/
String content = generatedJSONString;
/* Send the request data.*/
output.writeBytes(content);
output.flush();
output.close();
/* Get response data.*/
String response = null;
input = new DataInputStream (urlConn.getInputStream());
while (null != ((response = input.readLine()))) {
System.out.println(response);
input.close ();
}
}
My code so far with HttpClient is:
public static void SaveWorkflow() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(myUrlgoeshere);
StringEntity input = new StringEntity(generatedJSONString);
input.setContentType("application/json;charset=UTF-8");
postRequest.setEntity(input);
input.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
postRequest.setHeader("Accept", "application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
httpClient.getConnectionManager().shutdown();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Where generated JsonString is like this:
{"description":"prova_Process","modelgroup":"","modified":"false"}
The response I get is:
{"response":false,"message":"Error in saving the model. A JSONObject text must begin with '{' at 1 [character 2 line 1]","ids":[]}
Any idea please?
Finally I managed to find the solution to my problem ...
public static void SaveWorkFlow() throws IOException
{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(myURLgoesHERE);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("task", "savemodel"));
params.add(new BasicNameValuePair("code", generatedJSONString));
CloseableHttpResponse response = null;
Scanner in = null;
try
{
post.setEntity(new UrlEncodedFormEntity(params));
response = httpClient.execute(post);
// System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
in = new Scanner(entity.getContent());
while (in.hasNext())
{
System.out.println(in.next());
}
EntityUtils.consume(entity);
} finally
{
in.close();
response.close();
}
}
Another way to achieve this is as shown below:
public static void makePostJsonRequest(String jsonString)
{
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost postRequest = new HttpPost("Ur_URL");
postRequest.setHeader("Content-type", "application/json");
StringEntity entity = new StringEntity(jsonString);
postRequest.setEntity(entity);
long startTime = System.currentTimeMillis();
HttpResponse response = httpClient.execute(postRequest);
long elapsedTime = System.currentTimeMillis() - startTime;
//System.out.println("Time taken : "+elapsedTime+"ms");
InputStream is = response.getEntity().getContent();
Reader reader = new InputStreamReader(is);
BufferedReader bufferedReader = new BufferedReader(reader);
StringBuilder builder = new StringBuilder();
while (true) {
try {
String line = bufferedReader.readLine();
if (line != null) {
builder.append(line);
} else {
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
//System.out.println(builder.toString());
//System.out.println("****************");
} catch (Exception ex) {
ex.printStackTrace();
}
}
I am using this code but i am not able to send the string array:
httpclient = new DefaultHttpClient();
httppost = new HttpPost(Call_Server.UPLOAD_VIDEO);
MultipartEntity mpEntity = new MultipartEntity(
HttpMultipartMode.STRICT);
mpEntity.addPart("FILE_UPLOAD", new FileBody(videofile));
mpEntity.addPart("from_email", new StringBody(
Call_Server.useremail));
mpEntity.addPart("recipient_emails", new StringBody(
AddressArray));
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
You can do something like this.
// Prepare Category Array
for (String mBusinessID : mSelectedCategoryArray) {
reqEntity.addPart("CategoryCBG[]", new StringBody(mBusinessID));
}
Just add [] with you array tag and paas values in a loop in it.
Here CategoryCBG is the array tag. You can pass your values in this tag by using loop. it will post as an array on server.
Here is the complete code how I used it :
public String executeMultipartPost() throws Exception {
try {
ByteArrayOutputStream mByteOutputStream = new ByteArrayOutputStream();
mSelectedImage.compress(CompressFormat.JPEG, 75, mByteOutputStream);
byte[] mImageByteDate = mByteOutputStream.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(CONSTANTS.MAIN_URL_GLOBAL + CONSTANTS.BUSINESS_REGISTRATION_TAG);
ByteArrayBody mImageByteArray = new ByteArrayBody(mImageByteDate, Long.toString(System.currentTimeMillis()) + ".jpg");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("logo_img", mImageByteArray);
reqEntity.addPart("name", new StringBody(txtBusinessName_business_registration.getText().toString()));
reqEntity.addPart("email", new StringBody(txtBusinessEmail_business_registration.getText().toString()));
reqEntity.addPart("contact_phone", new StringBody(txtBusinessPhone_business_registration.getText().toString()));
reqEntity.addPart("link_url", new StringBody(txtBusinessWebsite_business_registration.getText().toString()));
reqEntity.addPart("Address", new StringBody(txtStreetAddress_business_registration.getText().toString()));
reqEntity.addPart("City", new StringBody(txtCity_business_registration.getText().toString()));
reqEntity.addPart("State", new StringBody(txtState_business_registration.getText().toString()));
reqEntity.addPart("Zip", new StringBody(txtZip_business_registration.getText().toString()));
reqEntity.addPart("details", new StringBody(txtDetail_business_registration.getText().toString()));
reqEntity.addPart("products", new StringBody(txtService_business_registration.getText().toString()));
// Prepare Category Array
for (String mBusinessID : mSelectedCategoryArray) {
reqEntity.addPart("CategoryCBG[]", new StringBody(mBusinessID));
}
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
mStringBuilder = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
mStringBuilder = mStringBuilder.append(sResponse);
}
return mStringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
return "error";
}
}
Update
To cancel ongioing uploading you can use
httpClient.getConnectionManager().shutdown();