sending a post request apache and java - java

I have this code block that sends a post request to one of my localhost ports:
public String request(String name){
String responseString = null;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userName", name));
params.add(new BasicNameValuePair("passWord","123455"));
HttpPost post = new HttpPost("http://localhost:2332/getData/postData");
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new StringEntity(URLEncodedUtils.format(params,"UTF-8"), HTTP.UTF_8));
responseString = execute(post,params.toString());
return responseString;
}
public String execute(HttpRequestBase requestBase, String params){
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = null;
String responseString = "";
try {
LOG.info("Request Method:{}",requestBase.getMethod());
LOG.info("Request Parameters:{}",params);
response = httpClient.execute(requestBase);
HttpEntity entity = response.getEntity();
responseString = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
I think that this code block should work because I used a tutorial as a reference but whenever I run my application the value of responseString is null or the application doesn't show me any results. Is there something wrong with my code?

Related

Sending Https Request But Not Getting Response

I am sending Https request to mysql server but not getting the response while performing the same task on localhost it is working. I have no experience using Https, please give me solution and explain difference between Http and Https request sending to mysql server, hope someone help me thanks in advance.
This is my code
protected String doInBackground(String... params) {
String emailSend = params[0];
String tokenSend = params[1];
String deviceIdSend = params[2];
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", emailSend));
nameValuePairs.add(new BasicNameValuePair("token", tokenSend));
nameValuePairs.add(new BasicNameValuePair("deviceId", deviceIdSend));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://xyz/xyz/xyz.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
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);
}
result = sb.toString();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
#Override
protected void onPostExecute(String resultN) {
super.onPostExecute(resultN);
String s = resultN.trim();
//dialog.dismiss();
if (s.equalsIgnoreCase("success")) {
if (result.contains("Pass")) {

Sending a large String from Android to Servlet using Async Task

In my app I am sending a String to the Servlet through BasicNameValuePairs, this way:
HttpClient httpClient = new DefaultHttpClient(); //127.0.0.1 - 10.201.19.153
HttpPost httpPost = new HttpPost(conn.urls.get("now"));
List<NameValuePair> nameValuePairs = new ArrayList<>(1);
nameValuePairs.add(new BasicNameValuePair("order", order));//"tours"
if(order.equals("reservation")){
String booking = new Gson().toJson(reservation);
nameValuePairs.add(new BasicNameValuePair("reservation", booking));
}
try {
// Add name data to request
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
//...
} //...
is there another way to send a String apart from using BasicNameValuePairs or this is the only way?
I don't exactly know why u need an alternative but here it is ..
instead of using Gson u can use following code
{
...
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("string",longString));
makeHttpRequest(url,"POST", params);
...
}
public void makeHttpRequest(String url, String method, List<NameValuePair> params) {
try {
if (method == "POST"){
DefaultHttpClient httpClient= new DefaultHttpClient();
HttpPost httpPost =new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse=httpClient.execute(httpPost);
HttpEntity httpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}else if (method == "GET"){
DefaultHttpClient httpClient=new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params,"utf-8");
if (!paramString.matches(""))
{
url +="?"+paramString;
}
HttpGet httpGet = new HttpGet(url);
lru =url;
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I hope it helps

org.apache.http.client.ClientProtocolException appears when HttpClient executes

I want to send to server some data via POST-request. My code:
protected Void doInBackground(Void... arg)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://money.yandex.ru/oauth/authorize");
post.addHeader("Host", "m.sp-money.yandex.ru");
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
post.addHeader("Content-Length", "154");
//data back from server
String responseBackFromServer = "";
try
{
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("client_id", "51"));
pairs.add(new BasicNameValuePair("response_type", "code"));
pairs.add(new BasicNameValuePair("redirect_uri", "https://vk.com/"));
pairs.add(new BasicNameValuePair("scope", "account-info"));
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse server_response = httpclient.execute(post);//!!!exception is appearing here!!!
responseBackFromServer = EntityUtils.toString(server_response.getEntity());
}
catch (ClientProtocolException e)
{
e.printStackTrace();
Log.d(LOG_TAG, "" + e);
}
}
But on "HttpResponse server_response = httpclient.execute(post);" string ClientProtocolException appears. How can I fix it?
Try removing all the addHeader statements. The framework should add them for you.
See here for an example: https://hc.apache.org/httpcomponents-client-4.3.x/quickstart.html

Getting "Invalid JSON primitive" error while trying to get data from WebService

I'm working on an android app and I want to get some data from a WebService. I'm using this code to get JSON data from the WebService.
TextView textv=(TextView) findViewById(R.id.textv);
try {
HttpClient client = new DefaultHttpClient();
String URL = "http://server/WebService.asmx/Get_ActiveFair";
HttpPost post = new HttpPost(URL);
post.setHeader("Content-Type", "application/json; charset=utf-8");
HttpResponse responsePost = client.execute(post);
HttpEntity resEntityPost = responsePost.getEntity();
if (resEntityPost != null)
{
String response=EntityUtils.toString(resEntityPost);
Log.e("XXX",response);
textv.setText(response);
}
} catch (Exception e) {
e.printStackTrace();
textv.setText(e.toString());
Log.e("error!!",e.toString());
}
It works correctly an I get the data like this:
{
"d": "{\"Id\":2,\"Name\":\"Fair Name \",\"IsActive\":true,\"Date_Start\":\"\\/Date(1383343200000)\\/\",\"Date_End\":\"\\/Date(1384034400000)\\/\",\"Url_Map\":null,\"Details\":\"Fair Details \",\"Address\":\"FairAdress \",\"VisitingInfo\":\"Fair Visiting Info\",\"Contact\":null,\"Transportation\":\" Fair Transportation Info \"}"
}
But when I want to use another method in the webservice which needs to get FairId I get the result:
{
"Message": "Invalid JSON primitive: FairId.",
"StackTrace": " at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)",
"ExceptionType": "System.ArgumentException"
}
And here is my code to run the Get_EventList method:
TextView textv=(TextView) findViewById(R.id.textv);
try {
HttpClient client = new DefaultHttpClient();
String URL = "http://server/WebService.asmx/Get_EventList";
HttpPost post = new HttpPost(URL);
List<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("FairId", "2"));
post.setEntity(new UrlEncodedFormEntity(postParameters));
post.setHeader("Content-Type", "application/json; charset=utf-8");
HttpResponse responsePost = client.execute(post);
HttpEntity resEntityPost = responsePost.getEntity();
if (resEntityPost != null)
{
String response=EntityUtils.toString(resEntityPost);
Log.e("XXX",response);
textv.setText(response);
}
} catch (Exception e) {
e.printStackTrace();
textv.setText(e.toString());
Log.e("hata!!",e.toString());
}
What can be the problem? How can I solve it?
I solve the problem by sending FairId to WebService with JSONObject. Here is my new code:
TextView textv=(TextView) findViewById(R.id.textv);
try {
HttpClient client = new DefaultHttpClient();
String URL = "http://server/WebService.asmx/Get_EventList";
HttpPost post = new HttpPost(URL);
JSONObject json = new JSONObject();
json.put("FairId", "2");
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse responsePost = client.execute(post);
HttpEntity resEntityPost = responsePost.getEntity();
if (resEntityPost != null)
{
String response=EntityUtils.toString(resEntityPost);
Log.e("XXX",response);
textv.setText(response);
}
} catch (Exception e) {
e.printStackTrace();
textv.setText(e.toString());
Log.e("hata!!",e.toString());
}

Send key-value parametres and json message body throught http post request

I need to send http POST request from mobile android application to the server side applcation.
This request need to contain json message in body and some key-value parametres.
I am try to write this method:
public static String makePostRequest(String url, String body, BasicHttpParams params) throws ClientProtocolException, IOException {
Logger.i(HttpClientAndroid.class, "Make post request");
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(body);
httpPost.setParams(params);
httpPost.setEntity(entity);
HttpResponse response = getHttpClient().execute(httpPost);
return handleResponse(response);
}
Here i set parametres to request throught method setParams and set json body throught setEntity.
But it isn't work.
Can anybody help to me?
You can use a NameValuePair to do this..........
Below is the code from my project where I used NameValuePair to sent the xml data and receive the xml response, this will provide u some idea about how to use it with JSON.
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now",sb+"");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sb.toString());
return sb.toString();
}

Categories