got empty string from json in android - java

So when i use postman(google app) to send a post method to my php file on my web server, i got a full respond back with all the correct information. but when i am trying to do the same thing on android, i am getting [] in response everytime.
#Override
protected Profile doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("name", user.name));
dataToSend.add(new BasicNameValuePair("password", user.password));
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost post = new HttpPost("http://www.secretvoice1.com/getData.php");
Profile returnUser = null;
try {
HttpResponse httpResponse = client.execute(post);
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
HttpEntity entity = httpResponse.getEntity();
Log.d("11111:", httpResponse.toString());
String result = EntityUtils.toString(entity);
System.out.println(result);
Log.d("222222", result);
JSONObject jsonObject = new JSONObject(result);
if (jsonObject.length() == 0) {
returnUser = null;
Log.d("this:", "here");
} else {
//String name = jsonObject.getJSONArray("name");
//String password = jsonObject.getString("password");
//String email = jsonObject.getString("email");
returnUser = new Profile(user.name, user.password, user.email);
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}

Related

How can I log in this site using java?

I was trying to log in this site using HttpClient:
https://translator.wiitrans.cn/
After trying all day, I just can not get the logged page. This is my code:
public class SimpleClient {
static String code = "";
static String captchaUrl= "https://passport.wiitrans.cn/code";
public static void logIn() throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
// HttpGet httpGet = new HttpGet("https://passport.wiitrans.cn/");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("account", xxxxx));
formparams.add(new BasicNameValuePair("password", xxxxx));
formparams.add(new BasicNameValuePair("code", code));
formparams.add(new BasicNameValuePair("autologin", "1"));
UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(formparams, "UTF-8");
HttpPost httppost = new HttpPost("https://passport.wiitrans.cn/");
httppost.setEntity(entity1);
HttpResponse response = httpclient.execute(httppost);
String set_cookie = response.getFirstHeader("Set-Cookie").getValue();
System.out.println(set_cookie.substring(0, set_cookie.indexOf(";")));
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++=");
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++=");
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++=");
HttpGet httpget = new HttpGet("https://translator.wiitrans.cn/");
httpget.setHeader("Cookie", set_cookie);
HttpResponse response2 = httpclient.execute(httpget);
HttpEntity entity2 = response2.getEntity();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity2.getContent()));
String line = "";
while((line = bufferedReader.readLine()) != null){
System.out.println(line);
}
}
public static void main(String[] args){
code = Captcha.getCaptcha(captchaUrl);
try {
logIn();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The captcha is downloaded and input manually, can anyone help me fix this?

Why does not my HTTP Connection timeout?

I have the following code for doing a HTTP Post:
InputStream ins = null;
String result = null;
public String postforBakup(String url){
java.util.Date date= new java.util.Date();
Timestamp timestamp = (new Timestamp(date.getTime()));
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient http = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
try{
JSONArray json = (makeJSON());
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("key", processKey()));
nameValuePairs.add(new BasicNameValuePair("type", "Android"));
nameValuePairs.add(new BasicNameValuePair("timestamp", timestamp.toString()));
nameValuePairs.add(new BasicNameValuePair("mail", mail));
nameValuePairs.add(new BasicNameValuePair("jsonArray", Arrays.asList(json).toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse resp = http.execute(httppost);
HttpEntity entity = resp.getEntity();
ins = entity.getContent();
BufferedReader bufread = new BufferedReader(new InputStreamReader(ins, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = bufread.readLine()) != null){
sb.append(line +"\n");
}
result = sb.toString().trim();
System.out.println("Response: "+result);
}catch (Exception e){
System.out.println("Squish: "+e);
}finally{
try{
if(ins != null){
ins.close();
}
}catch(Exception smash){
System.out.println("Squish: "+smash);
}
}
if(result.equalsIgnoreCase("Authentication failed")){
System.out.println("Death");
return "Backup failed";
}else if (result.equalsIgnoreCase("update successfull")){
System.out.println("Life");
return "Success";
}else{
return "failed";
}
}
While as the function works properly if connected to WIFI, when I switch to 2g I get the loader for hours without any exception or a message of timeout. What is possibly wrong here?

How to do POST request and get a response from server?

I need to do a POST request to SERVER by such example:
REQUEST FORMAT:
POST /oauth/authorize HTTP/1.1
Host: m.sp-money.yandex.ru (для мобильных устройств) или sp-money.yandex.ru (для остальных устройств)
Content-Type: application/x-www-form-urlencoded
Content-Length: <content-length>
client_id=<client_id>&response_type=code
&redirect_uri=<redirect_uri>&scope=<scope>
REQUEST PARAMETERS EXAMPLE:
client_id=092763469236489593523464667
response_type=code
redirect_uri=https://client.example.com/cb
scope=account-info operation-history
Now, I have been done a transfer for headers:
protected Void doInBackground(Void... arg)
{
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("HOST", "sp-money.yandex.ru"));
params.add(new BasicNameValuePair("Content-Type", "application/x-www-form-urlencoded"));
params.add(new BasicNameValuePair("Content-Length", "154"));
JSONObject testJSON = makeHttpRequest("https://money.yandex.ru/oauth/authorize", "POST", params);
int test = 1;
return null;
}
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params)
{
try
{
if(method == "POST")
{
String responseText = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
String testStr = httpPost.toString();
HttpResponse httpResponse = httpClient.execute(httpPost);
responseText = EntityUtils.toString(httpResponse.getEntity());
int test = 1;
test = 0;
}
}
//.............................................
}
How can I do a transfer for parameters(client_id, response_type, redirect_uri, scope)?
And how can I get response from server?
RESPONSE EXAMPLE:
HTTP/1.1 302 Found
Location: https://client.example.com/cb?code=i1WsRn1uB1ehfbb37
In your doInBackground you can try something like this.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(HTTP_REQUEST_URL);
//create and assign post request server data
String latitude = loc.getLatitude() + "";
String longitude = loc.getLongitude() + "";
String time = DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()) + "";
String whr = WhereAmI(loc.getLatitude(), loc.getLongitude());
//data back from server
String responseBackFromServer = "";
try {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("latitude", latitude));
pairs.add(new BasicNameValuePair("longitude", longitude));
pairs.add(new BasicNameValuePair("whereAmI", whr));
pairs.add(new BasicNameValuePair("time", time));
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse server_response = client.execute(post);
responseBackFromServer = EntityUtils.toString(server_response.getEntity());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return "Response Back: " + responseBackFromServer;
and In onPostExecute you can do whatever with the reponse.

Android - How to upload video/image to PHP Server

I am able to post string values to PHP server by using the following code:
public void callWebService(String strEmailList){
HttpResponse response = null;
String responseBody="";
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6);
nameValuePairs.add(new BasicNameValuePair("stringkey1",
String_Value1));
nameValuePairs.add(new BasicNameValuePair("stringkey2", String_Value2));
nameValuePairs.add(new BasicNameValuePair("stringkey3", String_Value3));
nameValuePairs.add(new BasicNameValuePair("stringkey4", String_Value4));
nameValuePairs.add(new BasicNameValuePair("stringkey5", String_Value5));
nameValuePairs.add(new BasicNameValuePair("stringkey6", Here i need to post Image));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://MY URL");
if (nameValuePairs != null)
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handleResponse(responseBody);
}
I am getting responseBody perfectly if i post only string values. In the nameValuePair, I need to post Image to Server. Can anyone help me how to post image using following code.
You can send image to the server as a Multipart entity
public void upload(String filepath) throws IOException
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("url");
File file = new File(filepath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
// check the response and do what is required
}
For uploading image and Video,,, you need to use MultiPart.First you need to Attach your file in fileBody which later attach in Multipart
public JSONObject file_upload1(String URL, String userid, String topic_id,
String topicname, String filelist, String taglist,
String textComment, String textLink) {
JSONObject jObj = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
FileBody bin = null;
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(filelist);
try {
bin = new FileBody(file);
} catch (Exception e) {
e.printStackTrace();
}
reqEntity.addPart("post_data" + i, bin);
reqEntity.addPart("tag", new StringBody("savetopicactivities"));
reqEntity.addPart("user_id", new StringBody(userid));
reqEntity.addPart("text", new StringBody(textComment));
reqEntity.addPart("count",
new StringBody(String.valueOf(taglist.size())));
reqEntity.addPart("topic_id", new StringBody(topic_id));
reqEntity.addPart("topic_name", new StringBody(topicname));
reqEntity.addPart("link", new StringBody(textLink));
httpPost.setEntity(reqEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
try {
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");
}
json = sb.toString();
System.out.println("json " + json);
try {
jObj = new JSONObject(json);
} catch (Exception e) {
e.printStackTrace();
}
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// return JSON String
return jObj;
}
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for (int index = 0; index < nameValuePairs.size(); index++)
{
if (index == nameValuePairs.size()-1)
{
entity.addPart(nameValuePairs.get(index).getName(),
new FileBody(new File(nameValuePairs.get(index)
.getValue())));
} else {
entity.addPart(nameValuePairs.get(index).getName() , new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity resEntity = response.getEntity();
if (resEntity != null)
{
String resdata = EntityUtils.toString(resEntity);
System.out.println("DATA :" + resdata);
}
} catch (IOException e) {
e.printStackTrace();
}

Android :-Consume a web service through Post method as a json Request and Response

My web service code is following i am using WCF Restful webservices,
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "Login?parameter={parameter}")]
string Login(string parameter);
public string Login(string parameter)
{
/*
* input := {"username":"kevin","password":"123demo"}
* output:= 1=sucess,0=fail
*
*/
//Getting Parameters from Json
JObject jo = JObject.Parse(parameter);
string username = (string)jo["username"];
string password = (string)jo["password"];
return ""+username;
}
my client side(Android) code is following
JSONObject json = new JSONObject();
try {
json.put("username","demo");
json.put("password","password123");
HttpPost postMethod = new HttpPost(SERVICE_URI);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
nameValuePairs.add(new BasicNameValuePair("parameter",""+json.toString()));
HttpClient hc = new DefaultHttpClient();
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = hc.execute(postMethod);
Log.i("response", ""+response.toString());
HttpEntity entity = response.getEntity();
final String responseText = EntityUtils.toString(entity);
string=responseText;
Log.i("Output", ""+responseText);
}
catch (Exception e) {
// TODO Auto-generated catch block
Log.i("Exception", ""+e);
}
I am getting following output after calling Web service:
The server encountered an error processing the request. See server
logs for more details.
Basically my problem is I am unable to pass value by using NameValuePair.
Following code worked for me:
public static String getJsonData(String webServiceName,String parameter)
{
try
{
String urlFinal=SERVICE_URI+"/"+webServiceName+"?parameter=";
HttpPost postMethod = new HttpPost(urlFinal.trim()+""+URLEncoder.encode(parameter,"UTF-8"));
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
HttpClient hc = new DefaultHttpClient();
HttpResponse response = hc.execute(postMethod);
Log.i("response", ""+response.toString());
HttpEntity entity = response.getEntity();
final String responseText = EntityUtils.toString(entity);
string=responseText;
Log.i("Output", ""+responseText);
}
catch (Exception e) {
}
return string;
}

Categories

Resources