[萌新]询问这个函数怎么调用!

Android 码拜 9年前 (2016-01-30) 1100次浏览
android studio

    public static String testGetHtml(String urlpath) throws Exception {
        URL url = new URL(urlpath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(6 * 1000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == 200) {
            InputStream inputStream = conn.getInputStream();
            byte[] data = readStream(inputStream);
            String html = new String(data);
            return html;
        }
        return null;
    }
button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new Button.OnClickListener()
        {
            @Override
            public void onClick(View v)  {
                // 试图在这里调用,直接就出波浪线报错了unhandled exception java.lang.exception
                testGetHtml("http://192.168.0.2:81/");
                DisplayToast("a");
            }
        });
解决方案:20分
testGetHtml(“http://192.168.0.2:81/”);
改为
try{
testGetHtml(“http://192.168.0.2:81/”);
}catch(Exception e) {
e.printStackTrace();
}
解决方案:20分
访问网络 必须写在 新线程里
另外 你还要测试下 http://192.168.0.2:81/  能否能访问 能否存在网页代码错误
本人正在用的 代码  你改改就能用

public void startpost(
String url,
String[] namel,String[] valuel
 , boolean isurlcoed ,Bitmap bitmap,boolean showProgress )
{
 
 httpupload mhttpupload = new httpupload(
 url,namel,valuel,isurlcoed,bitmap,showProgress
 );    //假如有中文 则 urlcoed   code
	mhttpupload.execute();   
}
  
private final class httpupload extends 
AsyncTask<Object, Integer, Void> {  
     private   HttpURLConnection connection  ;  
	 private   DataOutputStream outputStream  ;  
	 private   InputStream inputStream  ;  	 
	 private  StringBuffer sbf  ;  //返回值 
     private ProgressDialog dialog  ;  
//=========================================	 
		private  String[] namelist;
		private  String[] valuelist; 
		private  Bitmap uploadFile;
		private  String urltxt;
		private  boolean showProgress ;
		private  boolean isurlcode ;
 
public httpupload(String urlin,String[] namelin
 ,String[] valuelin, boolean isurlcoedin 
 ,Bitmap bitmapin, boolean showProgressin){
 urltxt=urlin; namelist=namelin;
 valuelist=valuelin; isurlcode= isurlcoedin ;
 uploadFile =bitmapin; showProgress=showProgressin;
}
@Override  
protected void onPreExecute() {  
	 
	// Log.i("uploadFile","开始上传" );   
	 if(showProgress && dialog==null){
    dialog = new ProgressDialog(mct);  
    dialog.setMessage(saf.res.getString(R.string.sjking));  
    dialog.setCanceledOnTouchOutside(false);
    dialog.setIndeterminate(false);  
    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
    dialog.setProgress(0);  
    dialog.show();  
	 }
}  
@Override  
protected Void doInBackground(Object... arg0) { 
	 InputStream InputStream = null ;
	 // FileInputStream fileInputStream = null ;
  
    long length = 0;  
    int progress;   
    
	// Log.i("uploadFile","新线程开始" );  
	    try {  
 URL url = new URL(urltxt);  
 connection = (HttpURLConnection) url.openConnection();   
 //connection.setChunkedStreamingMode(Chunkedsize);   
 //connection.setChunkedStreamingMode(1);
 connection.setRequestProperty("Connection", "Keep-Alive"); 
 connection.setDoInput(true);  
   connection.setRequestMethod("POST");   
   connection.setUseCaches(false);  
   connection.setInstanceFollowRedirects(true); 
  connection.setRequestProperty("Content-Type",  
   "multipart/form-data;boundary=" + boundary); 
  connection.setDoOutput(true);    
connection.setRequestProperty("Charset", "gbk");  
        connection.setConnectTimeout(8000);  
        connection.setReadTimeout(8000); 
 connection.connect();  
  
outputStream = new DataOutputStream(  
   connection.getOutputStream());  //conne连接 
  
//能否urldecode
 if(isurlcode){
 outputStream.writeBytes(twoHyphens + boundary + lineEnd+
"Content-Disposition: form-data; name="isurlcode""+lineEnd+
lineEnd+"true" + lineEnd ); 
 }
 
 //写入表单正式内容
 if(namelist!=null){
 int  len=namelist.length;
 for(int i = 0;i < len;i++)
 { 
 outputStream.writeBytes(twoHyphens + boundary + lineEnd+
 "Content-Disposition: form-data; name=""+namelist[i]+""" 
 +lineEnd+lineEnd);   
 
 if(isurlcode){
	 outputStream.writeBytes(
     URLEncoder.encode(valuelist[i], "gbk") 
	 + lineEnd);    
 }else{
	 outputStream.writeBytes( valuelist[i] + lineEnd);     
 }
 }
 }
 //写入表单 over
 
//Log.i("uploadFile"," 表单数据写入ok:" );  
//=================================
//上传文件
if(uploadFile!=null){ 
	InputStream  = Bitmap2IS(uploadFile);
   //fileInputStream = new FileInputStream(uploadFile);   
   int bytesRead, bytesAvailable, bufferSize;  
   byte[] buffer;   
   long totalSize = bmpsize;   
 outputStream.writeBytes(twoHyphens + boundary + lineEnd);    
outputStream.writeBytes(
"Content-Disposition: form-data;name="file";filename=""
+ valuelist[valuelist.length-1]  + """ + lineEnd);  
outputStream.writeBytes(lineEnd);   
//bytesAvailable = fileInputStream.available();  
//bufferSize = Math.min(bytesAvailable, maxBufferSize);  
bufferSize = Chunkedsize ;   
buffer = new byte[bufferSize];  
//Read file  
//bytesRead = fileInputStream.read(buffer, 0, bufferSize);   
  bytesRead = InputStream.read(buffer, 0, bufferSize);   
if(showProgress){ 
while (bytesRead > 0) {   
outputStream.write(buffer, 0, bufferSize);  
length += bufferSize;  
 progress = (int) ((length * 70) / totalSize);  
publishProgress(progress);  
//bytesAvailable = fileInputStream.available();  
bytesAvailable =InputStream.available();  
bufferSize = Math.min(bytesAvailable, Chunkedsize);  
//bytesRead = fileInputStream.read(buffer, 0, bufferSize);  
bytesRead = InputStream.read(buffer, 0, bufferSize);   
}    
}  else{ 
while (bytesRead > 0) {   
outputStream.write(buffer, 0, bufferSize);  
length += bufferSize;   
//bytesAvailable = fileInputStream.available();  
bytesAvailable = InputStream.available();  
bufferSize = Math.min(bytesAvailable, Chunkedsize);  
//bytesRead = fileInputStream.read(buffer, 0, bufferSize);  
bytesRead = InputStream.read(buffer, 0, bufferSize);  
        }   
}
outputStream.writeBytes(lineEnd); 
outputStream.writeBytes( twoHyphens 
+ boundary + twoHyphens + lineEnd); 
 //Log.i("uploadFile"," 写入文件数据ok" );  
 
}
//Log.i("uploadFile","数据flush" );  
       outputStream.flush();  
        outputStream.close();   
//Log.i("uploadFile","数据flush ok close fileinput" );  
/* 取得Response内容 */  
 
//=--
inputStream = connection.getInputStream();  
//Log.i("uploadFile","取得input" );  
 if (connection.getResponseCode()==200){ 
	int ch;  
	 sbf = new StringBuffer();  
	while ((ch = inputStream.read()) != -1) {  
	sbf.append((char) ch);  
	}    
 //Log.i("接收返回内容",""+sbf.toString().trim()); 
	}else{
 Log.i("接收返回内容失败",""+connection.getResponseCode()); 
	} 	
 
 
 if(showProgress)  publishProgress(100);  
if(uploadFile!=null){
//fileInputStream.close();
 InputStream.close();
}
}
catch(Exception ex){
  	 Log.i("uploadFile4","失败"+ex );  	
}
 		
 if (connection!= null) connection.disconnect(); 
    
    return null;  
}  
@Override  
protected void onProgressUpdate(Integer... progress) {  
    dialog.setProgress(progress[0]);  
}  
@Override  
protected void onPostExecute(Void result) { 
	
	 mhttpokinter.httpok( sbf);  //把 返回值 传递给接口
	if(showProgress){
     dialog.dismiss();  		
	}
	
}  
}  	
	

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明[萌新]询问这个函数怎么调用!
喜欢 (0)
[1034331897@qq.com]
分享 (0)