我目前正在尝试通过http Get调用服务器进行身份验证。下面提供的代码在java项目中编译时有效。将正确的令牌返回给程序。但是,每当我尝试在Android中实现相同的代码时,我都不会通过Get调用返回令牌。
在Android中,我在函数中返回inputLine,但inputLine始终为空字符串。
system.out.println()打印返回的标记。
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();
}
}
}
感谢您的帮助!!!
答案 0 :(得分:2)
您可能没有将Internet-Permission添加到项目AndroidManifest.xml中。
如果是这样,请将以下行添加为<manifest/>
节点的子节点:
<uses-permission android:name="android.permission.INTERNET" />
答案 1 :(得分:2)
我正在使用POST和FormEntity从服务器检索数据(例如身份验证),我从来没有遇到任何问题:
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());
[...]
也许你会发现这个有用的