Https 请求,Android 中的身份验证 [英] Https request, authentication in Android
问题描述
我目前正在尝试通过 http Get 调用向服务器进行身份验证.下面提供的代码在 java 项目中编译时有效.将正确的令牌返回给程序.但是,每当我尝试在 Android 中实现相同的代码时,我都不会通过 Get 调用返回令牌.
I am currently trying to authenticate with a server via a http Get call. The code provided below works when compiled in a java project. Returning the correct token to the program. However whenever I try to implement the same code in Android I do not get a token returned via the Get call.
在 Android 中,我在函数中返回 inputLine,但 inputLine 始终为空字符串.
In Android I am returning inputLine in a function, however inputLine is always an empty string.
system.out.println() 打印返回的令牌.
The system.out.println() prints the returned token.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class JavaHttpsExample
{
public static void main(String[] args)
{ String inputLine = new String();
try
{
String httpsURL = "https://the url";
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
InputStream ins = con.getInputStream();
InputStreamReader isr=new InputStreamReader(ins);
BufferedReader in =new BufferedReader(isr);
inputLine = in.readLine();
System.out.println(inputLine);
in.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
感谢您的帮助!!!
推荐答案
我使用 POST 和 FormEntity 从服务器检索数据(例如身份验证),我从来没有遇到任何问题:
I'm using POST and FormEntity for retrieving data from the server (such as authentication), and i have never had any problems:
final String httpsURL = "https://the url";
final DefaultHttpClient client = new DefaultHttpClient();
final HttpPost httppost = new HttpPost(httpsURL);
//authentication block:
final List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair("userName", userName));
nvps.add(new BasicNameValuePair("password", password));
final UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
httppost.setEntity(p_entity);
//sending the request and retrieving the response:
HttpResponse response = client.execute(httppost);
HttpEntity responseEntity = response.getEntity();
//handling the response: responseEntity.getContent() is your InputStream
final InputSource inputSource = new InputSource(responseEntity.getContent());
[...]
也许你会觉得这很有用
这篇关于Https 请求,Android 中的身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!